var ctx = localStorage.getItem("ctx");
var wholeprovinceId = '';
var wholecityId = '';
var wholestatusId = '';
var table = '';
var searchcompanyname = '';
$(function(){
	
	juicer.set({
	    'tag::operationOpen': '-~',
	    'tag::operationClose': '+',
	    'tag::interpolateOpen': '#-',
	    'tag::interpolateClose': '+',
	    'tag::noneencodeOpen': '##-',
	    'tag::noneencodeClose': '+',
	    'tag::commentOpen': '-*',
	    'tag::commentClose': '+'
	});
	
	//日期设置一个默认时间
	$(".comdurstart").val(getNowFormatDate());
	$(".comdurend").val(getNowFormatDate());
	
	var wholeorganizationId = '';
	
	
	var isAdmin = localStorage.getItem('isAdmin');
	console.log(isAdmin);
	if(isAdmin == 'false') {
		$(".isAdminProvince").hide();
		$(".isAdminCity").hide();
	}
	
	//获取公司列表表格
	companyTable(wholeprovinceId,wholecityId,wholestatusId,searchcompanyname);
	
	
	//查询
    $(".btn-search").on("click", function() {
    	wholeprovinceId = $(".provinceSelect").find("option:selected").attr("value");
    	wholecityId = $(".citySelect").find("option:selected").attr("value");
    	wholestatusId = $(".statusSelect").find("option:selected").attr("value");
    	searchcompanyname = $(".searchcompanyname").val();
    	table.destroy();
    	//查询获取公司列表表格
    	companyTable(wholeprovinceId,wholecityId,wholestatusId,searchcompanyname);
    	
    });
	
	
	//获取省份
    getProvince();
    getCity('');
    addgetProvince();
    editgetProvince();
    
    
    //根据选取的省份获取城市和公司
    $(".provinceSelect").on("change", function(){
    	var provinceId = $(this).attr("value");
    	getCity(provinceId);
    });
    
    $(".AddCompanyProvinceSel").on("change", function(){
    	var provinceId = $(this).attr("value");
    	addgetCity(provinceId);
    });
    
    $(".editCompanyProvinceSel").on("change", function(){
    	var provinceId = $(this).attr("value");
    	editgetCity(provinceId);
    });
    
    
    
    //添加公司里面如果公司类型选择了总公司则其没有上级机构
    $(".addCompanyType").on("change", function() {
//    	alert($(this).attr("value"));
//    	addgetCompany($(this).attr("value"));
    	if($(this).attr("value") == 0) {
    		$(".AddCompanyCompanySelRow").hide();
    	}
    	else {
    		$(".AddCompanyCompanySelRow").show();
    	}
    });
    
  //编辑公司里面如果公司类型选择了总公司则其没有上级机构
    $(".editCompanyType").on("change", function() {
//    	alert($(this).attr("value"));
//    	editgetCompany($(this).attr("value"));
    	if($(this).attr("value") == 0) {
    		$(".EditCompanyCompanySelRow").hide();
    	}
    	else {
    		$(".EditCompanyCompanySelRow").show();
    	}
    });
   
    
    //编辑详情里面如果上级机构选取了自身，提示
    $(".EditCompanyCompanySel").on("change", function() {
    	
    	if($(this).attr("value") == wholeorganizationId) {
    		alert('上级机构不能为本公司,请重新选择');
    	}
    	
    });
    

	//查看详情
	$(document).on( 'click', '.btn-detail', function () {
		
        var data = table.row( $(this).parents('tr') ).data();
        console.log(data);
        $(".province").html(data.proviceName);
        $(".city").html(data.cityName);
        $(".company").html(data.organizationName);
        
        var type = data.organizationType;
        if(type == 1) {
        	$(".detailcompanyType").html("出租车公司");
        	$(".companyParentRow").show();
        	$(".companyParent").html(data.parentOrganizationName);
        }
        else
        if(type == 2) {
        	$(".detailcompanyType").html("专车公司");
        	$(".companyParentRow").show();
        	$(".companyParent").html(data.parentOrganizationName);
        }
        else {
        	$(".detailcompanyType").html("总公司");
        	$(".companyParentRow").hide();
        }
        $(".address").html(data.organizationAddr);
        
        $(".companyLic").html(data.businessLicence);
        $(".contactName").html(data.contacts);
        $(".contactTel").html(data.contactsNumber);
        $(".email").html(data.contactsEmail);
        $(".companyDur").html(data.licenseStartDate+'--'+data.licenseEndDate);
        $(".beizhu").html(data.remarks);
        var status = data.organizationStatus;
        if(status == 1) {
        	$(".status").html("已启用");
        }
        else
        if(status == 2) {
        	$(".status").html("已禁用");
        }
        else {
        	$(".status").html("暂无状态");
        }
        $("#myModalDetail").modal('show');
    } );
    
    //编辑详情
    $(document).on('click', '.btn-edit', function() {
	
    	var data = table.row( $(this).parents('tr') ).data();
    	if(data.organizationType == 0) {
    		$(".EditCompanyCompanySelRow").hide();
    	}  
    	else {
    		$(".EditCompanyCompanySelRow").show();
    	}
    	wholeorganizationId = data.organizationId;
        console.log(data);
//        editgetCompany(data.organizationType);
        $(".editCompanyProvinceSel").find('option[value='+data.proviceId+']').attr('selected', true);
        
        $.ajax({
    		type: 'POST',
    		url: ctx+'/sys/v1/organization/listByType',
    		dataType: 'json',
    		data: {
    			organizationType: '-1'
    		},
    		success: function(data22) {
    			console.log(data22);
    			var company = {};
    			company.list = data22;
    			var companyTpl = document.getElementById("EditCompanyCompanySelTpl").innerHTML;
    			var companyhtml = juicer(companyTpl, company);
    			$(".EditCompanyCompanySel").html(companyhtml);
    			$(".EditCompanyCompanySel").find("option[value="+data.parentId+"]").attr('selected', true);
    		}
    	});
        $.ajax({
        	type: 'POST',
    		url: ctx+'/proandcity/v1/city',
    		dataType: 'json',
    		data: {
    			proviceId: data.proviceId
    		},
    		success: function(data1) {
    			var cityTpl = document.getElementById("editCompanyCitySelTpl").innerHTML;
    			var cityhtml = juicer(cityTpl, data1);
    			$(".editCompanyCitySel").html(cityhtml);	
    			$(".editCompanyCitySel").find('option[value='+data.sysCityId+']').attr('selected', true);
    		}
    	});
        $(".editcompanytruename").val(data.organizationName);
        $(".editCompanyType").find("option[value="+data.organizationType+"]").attr('selected', true);
        $(".editaddressInputAdd").val(data.organizationAddr);
        $(".editcompanyLicInputAdd").val(data.businessLicence);
        $(".editcontactNameInputAdd").val(data.contacts);
        $(".editcompanytel").val(data.contactsNumber);
        $(".editcompanyemail").val(data.contactsEmail);
        $(".editcompanybeizhu").val(data.remarks);
        $(".editcompanyduring").find('input').eq(0).val(data.licenseStartDate.substr(0,10));
        $(".editcompanyduring").find('input').eq(1).val(data.licenseEndDate.substr(0,10));
        $(".editcompanyState").find("input[value="+data.organizationStatus+"]").attr("checked", true);
        
        $("#myModalEdit").modal('show');
    	
    });
    
    
    //修改公司字段验证
    $("#editcompanyForm").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	editcompanytruename: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            editaddressInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            editcompanyLicInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^\d{15}$/,
            			message: '15位数字'
                    }
                }
            },
            editcontactNameInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    	message: '只能输入汉字或英文姓名'
                    }
                }
                
            },
            editcompanytel: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
            		regexp: {
            			regexp: /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/,
            			message: '请输入正确手机号码'
            		}
                }
            },
            editcompanyemail: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
                        message: '正确邮箱格式'
                    }
                }
            }
        }
	});

    //确认修改
    $(".save-edit-btn").on('click', function() {
    	confirmeditcompany();
    });

    //添加公司
    $(".btn-add").on("click", function() {
    	
    	var provinceIdd = $(".AddCompanyProvinceSel").find("option:selected").attr("value");
    	addgetCity(provinceIdd);
    	var comTypeId = $(".addCompanyType").find("option:selected").attr("value");
    	addgetCompany('-1');
    	
    	$("#myModalAdd").modal('show');
    	
    });
    
    //添加公司验证字段
    $("#addcompanyForm").
	bootstrapValidator({
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	companytruename: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            addressInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    } 
                }
            },
            contactNameInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                    	regexp: /^[a-zA-Z\u4e00-\u9fa5]+$/,
                    	message: '只能输入汉字或英文姓名'
                    }
                }
            },
            companyLicInputAdd: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^\d{15}$/,
                        message: '15位数字'
                    }
                }
                
            },
            companytel: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
            		regexp: {
            			regexp: /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/,
            			message: '正确手机号码格式'
            		}
                }
            },
            companyemail: {
            	validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
                        message: '正确邮箱格式'
                    }
                }
            }
        }
	});
    
    //确认添加公司
    $(".btn-addcompany").on("click", function() {	
    	confirmaddcompany();
    });
    
    //公司启用和禁用
    $(document).on('click', '.btn-forbid', function() {
    	var data = table.row( $(this).parents('tr') ).data();
    	
    	console.log(data);
    	if(data.organizationType == 0) {
    		$(this).attr('disabled', true);
    		alert("没有权限");
    	}
    	else {
    		wholeorganizationId = data.organizationId;
        	if(data.organizationStatus == 1) {
        		editStatus(wholeorganizationId, 2);
        	}
        	if(data.organizationStatus == 2) {
        		editStatus(wholeorganizationId, 1);
        	}
    	}
    	
    });
    
    //删除
    $(document).on('click', '.btn-delete', function() {
    	var data = table.row( $(this).parents('tr') ).data();
    	console.log(data);
    	if(data.organizationType == 0) {
    		$(this).attr('disabled', true);
    		alert("没有权限");
    	}
    	else {
    		wholeorganizationId = data.organizationId;
        	$.ajax({
        		type: 'POST',
        		url: ctx+'/sys/v1/organization/del',
        		dataType: 'json',
        		data: {
        			organizationId: wholeorganizationId
        		},
        		success: function(data) {
        			if(data == true) {
        				alert('删除成功');
        				location.replace(location.href);
        			}
        			else {
        				alert('删除失败');
        			}
        		}
        	});
    	}
    	
    });
    
    
    
    
    
    
	//编辑详情点击修改图片
    $("#imgInp").change(function(){
       readURL(this);
    });
    
    //添加公司点击修改图片
    $("#imgInp1").change(function() {
    	readURL1(this);
    });
	
    //确认添加公司
    function confirmaddcompany(){
    	$('#addcompanyForm').data('bootstrapValidator').validate();  
        if(!$('#addcompanyForm').data('bootstrapValidator').isValid()){  
            return ;  
        }
        var cityId = $(".AddCompanyCitySel").find('option:selected').attr('value');//城市Id
        var cityName = $(".AddCompanyCitySel").find('option:selected').html();//城市name
        var organizationName = $(".companytruename").val();//机构名称
        var organizationType = $(".companytype").find('option:selected').attr("value");//机构类型
        var organizationParent = organizationType == 0 ? 0 : $(".AddCompanyCompanySel").find('option:selected').attr("value");//上级机构id
        var organizationAddr = $(".addressInputAdd").val();//机构地址
        var businessLicence = $(".companyLicInputAdd").val();//营业执照
        var contacts = $(".contactNameInputAdd").val();//联系人
        var contactsNumber = $(".companytel").val();//联系电话
        var contactsEmail = $(".companyemail").val();//邮箱
        var remarks = $(".companybeizhu").val();//备注
        var licenseStartDate = $(".companyduring").find('input').eq(0).val();//执照起始日期
        var licenseEndDate = $(".companyduring").find('input').eq(1).val();//执照结束日期
        var organizationStatus = $(".companyState").find("input:checked").attr("value");//状态
        
        
        if(licenseStartDate.length < 5) {
        	alert("请选择执照起始日期");
        }
        else if(licenseEndDate.length < 5) {
        	alert("请选择执照结束日期");
        }
        else if(new Date(licenseStartDate.replace(/\-/g, "\/")) > new Date(licenseEndDate.replace(/\-/g, "\/"))) {
        	alert("执照起始日期不能大于执照结束日期");
        }
        else {
        	$.ajax({
                type: 'POST',
                url: ctx+'/sys/v1/organization/add',
                dataType: 'json',
                data: {
                    cityId: cityId,
                    cityName: cityName,
                    organizationName: organizationName,
                    organizationType: organizationType,
                    organizationAddr: organizationAddr,
                    businessLicence: businessLicence,
                    contacts: contacts,
                    contactsNumber: contactsNumber,
                    contactsEmail: contactsEmail,
                    remarks: remarks,
                    licenseStartDate: licenseStartDate+" 00:00:00",
                    licenseEndDate: licenseEndDate+" 00:00:00",
                    organizationStatus: organizationStatus,
                    parentId: organizationParent
                },
                success: function(data) {
                    console.log(data);  
                    alert('添加成功');
                    location.replace(location.href);

                },
                error: function(data) {
                    alert(data.responseJSON.message);
                }
            });
        }

    }
    
    //确认修改公司
    function confirmeditcompany() {
    	$('#editcompanyForm').data('bootstrapValidator').validate();  
        if(!$('#editcompanyForm').data('bootstrapValidator').isValid()){  
            return ;  
        }
        console.log(111222);
        var cityId = $(".editCompanyCitySel").find('option:selected').attr('value');//城市Id
    	var cityName = $(".editCompanyCitySel").find('option:selected').html();//城市name
    	var organizationName = $(".editcompanytruename").val();//机构名称
    	var organizationType = $(".editCompanyType").find('option:selected').attr("value");//机构类型
    	var organizationParent = organizationType == 0 ? 0 : $(".EditCompanyCompanySel").find('option:selected').attr("value");//上级机构id 
    	var organizationAddr = $(".editaddressInputAdd").val();//机构地址
    	var businessLicence = $(".editcompanyLicInputAdd").val();//营业执照
    	var contacts = $(".editcontactNameInputAdd").val();//联系人
    	var contactsNumber = $(".editcompanytel").val();//联系电话
    	var contactsEmail = $(".editcompanyemail").val();//邮箱
    	var remarks = $(".editcompanybeizhu").val();//备注
    	var licenseStartDate = $(".editcompanyduring").find('input').eq(0).val();//执照起始日期
    	var licenseEndDate = $(".editcompanyduring").find('input').eq(1).val();//执照结束日期
    	var organizationStatus = $(".editcompanyState").find("input:checked").attr("value");//状态
    	
    	if(licenseStartDate.length < 5) {
        	alert("请选择执照起始日期");
        }
        else if(licenseEndDate.length < 5) {
        	alert("请选择执照结束日期");
        }
        else if(new Date(licenseStartDate.replace(/\-/g, "\/")) > new Date(licenseEndDate.replace(/\-/g, "\/"))) {
        	alert("执照起始日期不能大于执照结束日期");
        }
    	else {
    		$.ajax({
    			type: 'POST',
    			url: ctx+'/sys/v1/organization/update',
    			dataType: 'json',
    			data: {
    				cityId: cityId,
    				cityName: cityName,
    				organizationName: organizationName,
    				organizationType: organizationType,
    				organizationAddr: organizationAddr,
    				businessLicence: businessLicence,
    				contacts: contacts,
    				contactsNumber: contactsNumber,
    				contactsEmail: contactsEmail,
    				remarks: remarks,
    				licenseStartDate: licenseStartDate+" 00:00:00",
    				licenseEndDate: licenseEndDate+" 00:00:00",
    				organizationStatus: organizationStatus,
    				organizationId: wholeorganizationId,
    				parentId: organizationParent
    			},
    			success: function(data) {
        			console.log(data);	
        			alert('修改成功');
        			location.replace(location.href);

        		},
        		error: function(data) {
        			alert(data.responseJSON.message);
        		}
    		});
    	}
    	
    }
    
    
});

/*编辑详情图片上传*/
function readURL(input) {
   if (input.files && input.files[0]) {
       var reader = new FileReader();
       reader.onload = function (e) {
           $('#blah').attr('src', e.target.result);
       }
       reader.readAsDataURL(input.files[0]);
   }
}

/*添加公司图片上传*/
function readURL1(input) {
   if (input.files && input.files[0]) {
       var reader = new FileReader();
       reader.onload = function (e) {
           $('#blah1').attr('src', e.target.result);
       }
       reader.readAsDataURL(input.files[0]);
   }
}


//获取省份
function getProvince() {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/pro',
		dataType: 'json',
		success: function(data) {
			
			var provinceTpl = document.getElementById("provinceSelectTpl").innerHTML;
			var provincehtml = juicer(provinceTpl, data);
			var newprovincehtml = "<option value=''>全部</option>" + provincehtml;
			$(".provinceSelect").html(newprovincehtml);
			
		}
	});
}


//根据省份获取城市(可以传空，代表全部)
function getCity(provinceId) {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/city',
		dataType: 'json',
		data: {
			proviceId: provinceId
		},
		success: function(data) {
			var cityTpl = document.getElementById("citySelectTpl").innerHTML;
			var cityhtml = juicer(cityTpl, data);
			var newcityhtml = "<option value=''>全部</option>" + cityhtml;
			$(".citySelect").html(newcityhtml);
			
		}
	});
}

//添加获取省份
function addgetProvince() {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/pro',
		dataType: 'json',
		success: function(data) {
			console.log(data);
			var provinceTpl = document.getElementById("AddCompanyProvinceSelTpl").innerHTML;
			var provincehtml = juicer(provinceTpl, data);
			$(".AddCompanyProvinceSel").html(provincehtml);
			
		}
	});
}


//添加根据省份获取城市(可以传空，代表全部)
function addgetCity(provinceId) {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/city',
		dataType: 'json',
		data: {
			proviceId: provinceId
		},
		success: function(data) {
			
			var cityTpl = document.getElementById("AddCompanyCitySelTpl").innerHTML;
			var cityhtml = juicer(cityTpl, data);
			$(".AddCompanyCitySel").html(cityhtml);
			
		}
	});
}

//添加根据公司类型获取公司
function addgetCompany(organizationType) {
	$.ajax({
		type: 'POST',
		url: ctx+'/sys/v1/organization/listByType',
		dataType: 'json',
		data: {
			organizationType: organizationType
		},
		success: function(data) {
			console.log(data);
			var company = {};
			company.list = data;
			var companyTpl = document.getElementById("AddCompanyCompanySelTpl").innerHTML;
			var companyhtml = juicer(companyTpl, company);
			$(".AddCompanyCompanySel").html(companyhtml);
		}
	});
}
//编辑根据公司类型获取公司
function editgetCompany(organizationType) {
	$.ajax({
		type: 'POST',
		url: ctx+'/sys/v1/organization/listByType',
		dataType: 'json',
		data: {
			organizationType: organizationType
		},
		success: function(data) {
			console.log(data);
			var company = {};
			company.list = data;
			var companyTpl = document.getElementById("EditCompanyCompanySelTpl").innerHTML;
			var companyhtml = juicer(companyTpl, company);
			$(".EditCompanyCompanySel").html(companyhtml);
		}
	});
}

//编辑获取省份
function editgetProvince() {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/pro',
		dataType: 'json',
		success: function(data) {
			
			var provinceTpl = document.getElementById("editCompanyProvinceSelTpl").innerHTML;
			var provincehtml = juicer(provinceTpl, data);
			$(".editCompanyProvinceSel").html(provincehtml);
			
		}
	});
}


//编辑根据省份获取城市(可以传空，代表全部)
function editgetCity(provinceId) {
	$.ajax({
    	type: 'POST',
		url: ctx+'/proandcity/v1/city',
		dataType: 'json',
		data: {
			proviceId: provinceId
		},
		success: function(data) {
			var cityTpl = document.getElementById("editCompanyCitySelTpl").innerHTML;
			var cityhtml = juicer(cityTpl, data);
			$(".editCompanyCitySel").html(cityhtml);	
		}
	});
}

//修改公司启禁
function editStatus(organizationId, state) {
	$.ajax({
		type: 'POST',
		url: ctx+'/sys/v1/organization/state',
		dataType: 'json',
		data: {
			organizationId: organizationId,
			state: state
		},
		success: function(data) {
			console.log(data);
			if(data == true) {
				alert('修改成功');
				location.replace(location.href);
			}
			else {
				alert('修改失败');
			}
		}
	});
}

//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}




